package com.ruoyi.system.utils;

import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * @ProjectName: back
 * @Package: com.ruoyi.system.utils
 * @ClassName: SignUtils
 * @Author: haiyue
 * @Description:
 * @Date: 2025/6/9 下午 3:05:56
 * @Version: 1.0
 */
public class SignUtils {
    /**
     * 使用商户私钥对内容进行签名
     * @param message 待签名的消息
     * @param privateKeyPath 私钥文件路径
     * @return 签名后的Base64编码字符串
     * @throws Exception 异常
     */
    public static String sign(String message, String privateKeyPath) throws Exception {
        InputStream inputStream = Files.newInputStream(new File(privateKeyPath).toPath());
        // 加载商户私钥
        PrivateKey privateKey = PemUtil.loadPrivateKey(inputStream);
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(privateKey);
        sign.update(message.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(sign.sign());
    }

    /**
     * 从PEM文件中加载私钥
     * @param filePath 私钥文件路径
     * @return 私钥对象
     * @throws Exception 异常
     */
    private static PrivateKey getPrivateKey(String filePath) throws Exception {
        try (InputStream inputStream = SignUtils.class.getClassLoader().getResourceAsStream(filePath)) {
            if (inputStream == null) {
                throw new FileNotFoundException("私钥文件不存在: " + filePath);
            }

            StringBuilder keyContent = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (!line.startsWith("-----BEGIN PRIVATE KEY-----") &&
                            !line.startsWith("-----END PRIVATE KEY-----")) {
                        keyContent.append(line);
                    }
                }
            }

            byte[] keyBytes = Base64.getDecoder().decode(keyContent.toString());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpec);
        }
    }
}
